package com.example.caorl.job1.conc0302.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ConditionDemo {
    final Lock lock = new ReentrantLock();
    final Condition notFull = lock.newCondition(); //生产锁
    final Condition notEmpty = lock.newCondition(); //消费锁

    final Object[] items = new Object[20];
    int putptr, takeptr, count;

    public void put(Object x) throws InterruptedException {
        lock.lock();
        try {
            // 当count等于数组的大小时，当前线程等待，直到notFull通知，再进行生产
            while (count == items.length) {
                System.out.println("生产已满，等待消费");
                notFull.await(); // 类比 Object#wait()
            }
            items[putptr] = x;
            if (++putptr == items.length) putptr = 0;
            ++count;
            System.out.println("生产后数量+++++++++++++++" + count);
            notEmpty.signal(); //类比Object#notify ()
        } finally {
            lock.unlock(); //生产完后释放锁
        }
    }

    public Object take() throws InterruptedException {
        lock.lock();
        try {
            // 当count为0，进入等待，直到notEmpty通知，进行消费。
            while (count == 0) {
                System.out.println("商品库已空，等待生产");
                notEmpty.await();
            }
            Object x = items[takeptr];
            if (++takeptr == items.length) takeptr = 0;
            --count;
            System.out.println("消耗后数量------------------" + count);
            notFull.signal();
            return x;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ConditionDemo conditionDemo = new ConditionDemo();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                try {
                    conditionDemo.put(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(() ->{
            for (int i=0;i<1000;i++){
                try {
                    Object take = conditionDemo.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}